#!/bin/bash
echo "please input this file in the project_folders"
echo "input the application_name,default to flaskr"
read appname
# null exist should use double []
if [[ $appname == '' ]];then
    appname=flaskr
fi

#make sure empty
pkill -9 uwsgi
rm -rf venv uwsgi privkey.key fullchain.cer

python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt
mkdir uwsgi
touch uwsgi/uwsgi.pid uwsgi/uwsgi.status
cat >uwsgi/uwsgi.ini<<-EOF
[uwsgi]
#端口号
socket=:5050
#项目目录
chdir=$(pwd)
#虚拟环境的路径
virtualenv=%(chdir)/venv 
#项目启动文件
module=$appname:app
#进程数量
processes=4
#线程数量
threads=2
#允许主进程
master=True
#使程序后台运行
daemonize=%(chdir)/uwsgi/Server.log
#python文件更新及时生效
py-autoreload=1
#pid和status文件
stats=%(chdir)/uwsgi/uwsgi.status
pidfile=%(chdir)/uwsgi/uwsgi.pid
EOF
uwsgi --ini uwsgi/uwsgi.ini
#run on boot
echo '#!/bin/bash'>/etc/rc.d/init.d/uwsgiauto
echo '#chkconfig: 2345 80 90'>>/etc/rc.d/init.d/uwsgiauto
echo 'description: uwsgi auto start'>>/etc/rc.d/init.d/uwsgiauto
echo "uwsgi --ini $(pwd)/uwsgi/uwsgi.ini">>/etc/rc.d/init.d/uwsgiauto
chmod +x /etc/rc.d/init.d/uwsgiauto
chkconfig --add uwsgiauto


#nginx
domain=www.whxukang.cn
basedomain=${domain#*.}

~/.acme.sh/acme.sh --installcert -d $basedomain \
        --key-file   $(pwd)/privkey.key \
        --fullchain-file $(pwd)/fullchain.cer

cat >/etc/nginx/conf.d/default.conf<<-EOF
server {
        listen 80;
        server_name $domain;
        location =/weixin/ {                # for weixin url use port 80
                include uwsgi_params;
                uwsgi_pass 127.0.0.1:5050;
        }
        location / {
            #rewrite  ^(.*)$  https://\$server_name\$1 permanent;
            return 301 https://\$server_name\$request_uri;
        }
}

server {
        listen 443 ssl;
        server_name $domain;
        ssl_certificate  $(pwd)/fullchain.cer;
        ssl_certificate_key $(pwd)/privkey.key;
        ssl_session_timeout 5m;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        location / {
                include uwsgi_params;
                uwsgi_pass 127.0.0.1:5050;
        }

        location /static  {
               alias $(pwd)/$appname/static;
        }
}

EOF
nginx -s reload
systemctl stop nginx
systemctl start nginx
